package io.coderyeah.ymcc.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import io.coderyeah.ymcc.constant.RedisConstants;
import io.coderyeah.ymcc.domain.BlackList;
import io.coderyeah.ymcc.dto.ShieldDTO;
import io.coderyeah.ymcc.enums.YmccSystemError;
import io.coderyeah.ymcc.exception.BusinessException;
import io.coderyeah.ymcc.mapper.BlackListMapper;
import io.coderyeah.ymcc.result.JSONResult;
import io.coderyeah.ymcc.service.IBlackListService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class BlackListServiceImpl extends ServiceImpl<BlackListMapper, BlackList> implements IBlackListService {
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;
    @Autowired
    private BlackListMapper mapper;

    @Override
    public JSONResult shield(ShieldDTO shieldDTO) {
        BlackList blackList = new BlackList();
        BeanUtils.copyProperties(shieldDTO, blackList);
        try {
            insert(blackList);
            // 删除redis缓存
            redisTemplate.delete(RedisConstants.CACHE_BLACKLIST);
        } catch (Exception e) {
            throw new BusinessException(YmccSystemError.ALREADY_SHIELD);
        }
        return JSONResult.success();
    }

    @Override
    public JSONResult list(ShieldDTO shieldDTO) {
        List<BlackList> value = (List<BlackList>) redisTemplate.opsForValue().get(RedisConstants.CACHE_BLACKLIST);
        if (value != null) {
            return JSONResult.success(value);
        }
        log.info("数据库获取BLACKLIST~~~~~~~~~~~~~~~~~~");
        Wrapper<BlackList> wrapper = new EntityWrapper<>();
        if (StrUtil.isNotBlank(shieldDTO.getKeyword())) {
            wrapper.like("ip", shieldDTO.getIp()).or().like("phone", shieldDTO.getPhone());
        }
        List<BlackList> lists = mapper.selectList(wrapper);
        // 添加进redis
        redisTemplate.opsForValue().set(RedisConstants.CACHE_BLACKLIST, lists);
        return JSONResult.success(lists);
    }

    @Override
    public JSONResult delete(Long id) {
        deleteById(id);
        // 删除redis缓存
        redisTemplate.delete(RedisConstants.CACHE_BLACKLIST);
        return JSONResult.success();
    }
}
